package com.icetech.eom.controller.sys;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.icetech.commonbase.ResultTools;
import com.icetech.commonbase.constants.CodeConstantsEnum;
import com.icetech.commonbase.domain.Page;
import com.icetech.commonbase.domain.response.ObjectResponse;
import com.icetech.eom.common.annotation.SystemLog;
import com.icetech.eom.common.constant.UserTypeEnum;
import com.icetech.eom.controller.BaseController;
import com.icetech.eom.controller.vo.CustomVo;
import com.icetech.eom.dao.sys.CustomDao;
import com.icetech.eom.dao.tx.DeviceDao;
import com.icetech.eom.dao.tx.UserDao;
import com.icetech.eom.domain.sys.Custom;
import com.icetech.eom.domain.sys.User;
import com.icetech.eom.domain.tx.Device;
import com.icetech.eom.service.sys.ICustomService;
import com.icetech.eom.service.utils.SecurityUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 客户管理 前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2019-06-11
 */
@RestController
@RequestMapping("/custom")
public class CustomController  extends BaseController {

    @Autowired
    private ICustomService customService;
    @Autowired
    private SecurityUtil securityUtil;
    @Autowired
    private CustomDao customDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private DeviceDao deviceDao;
    /**
     * 获取客户列表
     */
    @ApiOperation(value = "获取客户列表", notes = "根据查询信息获取客户列表，返回List<Custom>类型用户信息的JSON")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "searchKey", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "page", value = "当前页数", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页展示条数", paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/listpage",method = RequestMethod.GET)
    @SystemLog(description = "获取客户列表")
    public ObjectResponse<Page> getPageList(@RequestParam(value = "searchKey",defaultValue = "")String searchKey,
                                           @RequestParam(value = "page",defaultValue = "1")Integer page,
                                           @RequestParam(value = "pageSize",defaultValue = "20")Integer pageSize){
        //获取客户列表信息
        PageInfo<Custom> pageInfo = customService.selectByPage(searchKey, page, pageSize);
        return ResultTools.getPageResponse(pageInfo.getList(),pageInfo.getTotal(),pageInfo.getPages());
    }

    /**
     * 获取所有的客户信息
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ObjectResponse<List<Custom>> getList(){
        User currUser = securityUtil.getCurrUser();
        List<Custom> customs = Lists.newArrayList();
        if (currUser.getUserType().equals(UserTypeEnum.custom_manager.getType())){
            Custom custom = customDao.selectById(currUser.getOrgId());
            customs.add(custom);
        }else {
            QueryWrapper<Custom> queryWrapper = new QueryWrapper<>();
            customs = customDao.selectList(queryWrapper);
        }

        return ResultTools.success(customs);
    }

    /**
     * 增加客户
     */
    @ApiOperation(value = "客户添加", notes = "添加客户信息")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @SystemLog(description = "客户添加")
    public ObjectResponse add(@RequestBody CustomVo customVo){
        User user = securityUtil.getCurrUser();
        Custom custom = new Custom();
        BeanUtils.copyProperties(customVo, custom);
        custom.setCreateBy(user.getUserName());
        boolean isSuccess = customService.save(custom);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 编辑客户
     */
    @ApiOperation(value = "客户编辑", notes = "编辑客户信息")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @SystemLog(description = "客户编辑")
    public ObjectResponse edit(@RequestBody CustomVo customVo){
        User user = securityUtil.getCurrUser();
        Custom custom = new Custom();
        BeanUtils.copyProperties(customVo, custom);
        custom.setUpdateBy(user.getUserName());
        boolean isSuccess = customService.updateById(custom);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 删除客户
     */
    @ApiOperation(value = "客户删除", notes = "删除客户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "query", dataType = "int")
    })
    @RequestMapping(value = "/remove",method = RequestMethod.GET)
    @SystemLog(description = "客户删除")
    public ObjectResponse remove(@RequestParam("id")Long id){
        Custom custom = customService.getById(id);
        if (Objects.isNull(custom)){
            return ResultTools.fail(CodeConstantsEnum.ERROR_404.getCode(),CodeConstantsEnum.ERROR_404.getDesc());
        }
        //查看该客户下是否存在子账号或者子设备
        List<User> users = userDao.selectByCustomId(id);
        if (!CollectionUtil.isEmpty(users)){
            return ResultTools.fail(CodeConstantsEnum.ERROR_402.getCode(),"当前客户存在子用户,不允许删除");
        }
        List<Device> devices = deviceDao.selectByCustomId(id);
        if (!CollectionUtil.isEmpty(devices)){
            return ResultTools.fail(CodeConstantsEnum.ERROR_402.getCode(),"当前客户存在所属设备,不允许删除");
        }
        boolean isSuccess = customService.removeById(id);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }
    /**
     * 删除客户
     */
    @ApiOperation(value = "客户批量删除", notes = "批量删除客户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id组成的数组", paramType = "query", dataType = "int")
    })
    @SystemLog(description = "客户批量删除")
    @RequestMapping(value = "/batchremove",method = RequestMethod.GET)
    public ObjectResponse batchRemove(@RequestParam("ids") List<Long> ids){
        boolean isSuccess = customService.removeByIds(ids);
        return isSuccess?ResultTools.success(null):ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
    }

    /**
     * 导出操作
     */
    @ApiOperation(value = "客户批量导出", notes = "批量导出客户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "searchKey", value = "关键字", paramType = "query", dataType = "String")
    })
    @SystemLog(description = "客户批量导出")
    @RequestMapping(value = "/export",method = RequestMethod.GET)
    public ObjectResponse export(@RequestParam(value = "searchKey",defaultValue = "") String searchKey, HttpServletResponse response){
        try {
            Workbook workbook = customService.exportExcel(searchKey);
            String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + ".xls";
            setFileResponse(response, fileName);
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTools.fail(CodeConstantsEnum.ERROR.getCode(),CodeConstantsEnum.ERROR.getDesc());
        }
        return ResultTools.success(null);
    }
}
